package top.houry.im.server.handler.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.protobuf.TextFormat;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.houry.im.server.common.Server;
import top.houry.im.server.entity.UserFriend;
import top.houry.im.server.enums.ImServerResultEnum;
import top.houry.im.server.handler.ImServerMsgTypeHandler;
import top.houry.im.server.listener.ImServerNettyProcessorListener;
import top.houry.im.server.proto.ImMessage;
import top.houry.im.server.service.IUserFriendService;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service(value = "client.friends.req")
public class ImServerFriendsMsgHandlerImpl implements ImServerMsgTypeHandler {

    private IUserFriendService userFriendService;

    @Autowired
    public void setUserFriendService(IUserFriendService userFriendService) {
        this.userFriendService = userFriendService;
    }

    @Override
    public void processImMsg(ImMessage.Server server, ChannelHandlerContext ctx) {
        try {
            ImMessage.UserFriendsReq friendsReq = ImMessage.UserFriendsReq.parseFrom(server.getBytesData());
            log.info("[Req]-[ImServerFriendsMsgHandlerImpl]-[processImMsg]-[friendsReq:{}]", TextFormat.printToUnicodeString(friendsReq));

            String userId = friendsReq.getUserId();
            if (StrUtil.isBlank(userId)) {
                log.info("[ImServerFriendsMsgHandlerImpl]-[processImMsg]-[userId为空]");
                ImMessage.Server fail = Server.fail("server.friends.resp", ImServerResultEnum.REQ_PARAM_ERROR);
                ctx.writeAndFlush(fail).addListener(new ImServerNettyProcessorListener("请求好友列表"));
                return;
            }

            ImMessage.UserFriendsResp.Builder friendsResp = ImMessage.UserFriendsResp.newBuilder();
            friendsResp.addAllFriends(getFriends(userId));

            ImMessage.Server serverResp = Server.success("server.friends.resp", friendsResp.build().toByteString());
            ctx.writeAndFlush(serverResp).addListener(new ImServerNettyProcessorListener("请求好友列表"));

        } catch (Exception e) {
            log.error("[Exception]-[ImServerFriendsMsgHandlerImpl]-[processImMsg]", e);
            ImMessage.Server fail = Server.fail("server.friends.resp", ImServerResultEnum.SERVER_ERROR);
            ctx.writeAndFlush(fail).addListener(new ImServerNettyProcessorListener("请求好友列表"));
        }
    }

    private List<ImMessage.FriendInfo> getFriends(String userId) {
        List<UserFriend> userFriends = userFriendService.list(Wrappers.<UserFriend>lambdaQuery().eq(UserFriend::getUserId, userId).eq(UserFriend::getDelFlag, false));
        List<ImMessage.FriendInfo> friendInfos = new ArrayList<>(userFriends.size());
        userFriends.forEach(friend -> {
            ImMessage.FriendInfo.Builder friendInfo = ImMessage.FriendInfo.newBuilder();
            friendInfo.setFriendId(String.valueOf(friend.getFriendId()));
            friendInfo.setFriendNickName(friend.getFriendNickName());
            friendInfos.add(friendInfo.build());
        });
        return friendInfos;
    }
}
